package com.zkaler.commons.utils.http;

import com.zkaler.common.constants.global.CookieConstants;
import lombok.extern.log4j.Log4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@Log4j
public class CookieUtils {

	public static Map<String, Object> getMaps(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
                try {
                    map.put(cookie.getName(),  URLDecoder.decode(cookie.getValue(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage(),e);
                }
            }
		}
		return map;
	}

	public static void clearAll(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
	}

	public static void clear(HttpServletRequest request, HttpServletResponse response, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					cookie.setMaxAge(0);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
		}
	}

	/**
	 * 读取浏览器cookie中的信息
	 * 
	 * @param req
	 *            HttpServletRequest
	 * @param name
	 *            cookie的名字
	 * @return
	 */
	public static String getValue(HttpServletRequest req, String name) {
		Cookie cookies[] = req.getCookies();
		Cookie cookie = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (cookie == null)
					continue;
				if (cookie.getName().equalsIgnoreCase(name)) {
                    try {
                        return URLDecoder.decode(cookie.getValue(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        log.error(e.getMessage(),e);
                        return null;
                    }
                }
			}
		}
		return null;

	}

	/**
	 * 设置浏览器cookie
	 * 
	 * @param req
	 *            HttpServletRequest
	 * @param res
	 *            HttpServletRequest
	 * @param name
	 *            cookie的名字
	 * @param value
	 *            cookie的值
	 * @param maxAge
	 *            cookie保存时间，以秒为单位
	 */
	public static void setValue(HttpServletRequest req, HttpServletResponse res, String name, String value,
			int maxAge,String domain) {
        Cookie cookie = null;
        try {
            cookie = new Cookie(name, URLEncoder.encode(value,"utf-8"));
            cookie.setMaxAge(maxAge);
            cookie.setDomain(domain);
            cookie.setPath("/");
            setCookie(req, res, cookie);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(),e);
        }
	}

    /**
     * 设置浏览器cookie
     *
     * @param req
     *            HttpServletRequest
     * @param res
     *            HttpServletRequest
     * @param name
     *            cookie的名字
     * @param value
     *            cookie的值
     */
    public static void setValue(HttpServletRequest req, HttpServletResponse res, String name, String value,String domain) {
        setValue(req,res,name,value, CookieConstants.DEFAULT_MAX_AGE,domain);
    }

	/**
	 * 设置浏览器cookie
	 * @param req
	 * @param res
	 * @param cookie
     */
	public static void setCookie(HttpServletRequest req, HttpServletResponse res, Cookie cookie) {
		Cookie cookies[] = req.getCookies();
		Cookie ck = null;
		boolean hasCookie = false;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				ck = cookies[i];
				if (ck.getName().equals(cookie.getName())) {
					hasCookie = true;
					break;
				}
			}
		}
		if (hasCookie) {
			ck.setValue(cookie.getValue());
			ck.setMaxAge(cookie.getMaxAge());
			ck.setDomain(cookie.getDomain());
			ck.setPath(cookie.getPath());
		} else {
			ck = cookie;
		}
		res.addCookie(cookie);
	}
}
